package com.abel.cloud.gateway.filter;

import com.alibaba.fastjson.JSONArray;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.*;

/**
 * Author: Abel.lin
 * Date: 2021/5/12 14:25
 * Company: Abel Studio
 * Copyright: Copyright (c) 2017
 * Description: 全局过滤器
 */
@Slf4j
@Component
public class LogGatewayFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        log.info("=== request URI:{} ===", request.getURI());

        HttpHeaders headers = request.getHeaders();
        Set<Map.Entry<String, List<String>>> headerNames = headers.entrySet();
        headerNames.forEach(map->{
            log.info("header key:{}, val:{}", map.getKey(), JSONArray.toJSONString(map.getValue()));
        });

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
